<template>
    <div>
        <!-- 摄像展示要用video标签 -->
        <video ref="video" preload autoplay loop muted width="400"></video>
        <!-- 截取的照片用canvas标签展示 -->
        <canvas ref="canvas" width="300" height="300"></canvas>

    </div>
    <br>
    <div>
        <ElButton @click="openMedia">打开</ElButton>
        <ElButton @click="closeMedia">关闭</ElButton>
        <ElButton type="primary" @click="drawMedia">截取</ElButton>
    </div>

    <div>
        <h1>当前用户：</h1>
        <div>
            <div>FaceId--{{ userInfo?.FaceId }}</div>
            <div>Gender--{{ userInfo?.Gender }}</div>
            <div>PersonId--{{ userInfo?.PersonId }}</div>
            <div>PersonName--{{ userInfo?.PersonName }}</div>
        </div>
    </div>
</template>
  
<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElButton } from 'element-plus'
import { Loading } from "@element-plus/icons-vue"

//视频标签
const video = ref(null);
//canvas标签
const canvas = ref(null);
//拍照后捕获的视频画面
const imgSrc = ref("");
//匹配成功后的用户信息
const userInfo = ref();

//执行初始化操作
onMounted(() => {
    openMedia();
});

//初始化页面
function openMedia() {
    // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }
    // 标准的API
    navigator.mediaDevices
        .getUserMedia({
            video: true,
        })
        .then((stream) => {
            // 摄像头开启成功
            video.value.srcObject = stream;
            video.value?.play();
        })
        .catch((err) => {
            console.log("err", err);
        });
}

//关闭摄像头
function closeMedia() {
    video.value.srcObject.getTracks()[0].stop();
}

//点击截取执行
async function drawMedia() {
    const msg = ElMessage({
        message: "正在识别中...",
        icon: Loading,
        type: "info",
        duration: 0,
        showClose: false,
    })
    //获取到画布上下文对象
    const ctx = canvas.value?.getContext("2d");
    ctx?.clearRect(0, 0, canvas.value.width, canvas.value.height);
    //绘制视频画面
    ctx.drawImage(
        video.value,
        (canvas.value.width - canvas.value.width * (320 / 240)) / 2,
        0,
        canvas.value.width * (320 / 240),
        canvas.value.height
    );
    //图片转base64编码
    const base64 = canvas.value.toDataURL("image/jpeg");
    imgSrc.value = base64;

    //把base64编码发送到后端
    const { data } = await axios.post('http://127.0.0.1:3000/api/faceLogin', { base64: base64.split(',')[1] })
    msg.close()
    //匹配成功执行
    if (!data.code) {
        ElMessage.success(data.msg)
        console.log(data.data, 'data')
        //后端返回的用户信息
        userInfo.value = data.data
        //关闭摄像头
        closeMedia()
    } else {//匹配失败
        ElMessage.error(data.msg)
    }
}
</script>
  
<style scoped>
video {
    object-fit: cover;
    transform: scaleX(-1);
}

canvas {
    transform: scaleX(-1);
}
</style>
  
  